from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_user, login_required

from dao import admin_dao
from form.forms import Edit_user_form
from model.admin import Admin
from model.user import User
from form.forms import Admin_Login_form

admin_bp = Blueprint("admin", __name__)


@admin_bp.route("/admin/")
@login_required
def list_User():
    users = admin_dao.queryUser()
    return render_template('console/index.html', users=users)


@admin_bp.route("/admin/deleteUser/<int:id>")
@login_required
def del_User(id):
    admin_dao.deleteUserById(id)
    return redirect(url_for('admin.list_User'))


@admin_bp.route("/admin/help")
@login_required
def help():
    return render_template("console/help.html")


@admin_bp.route("/admin/editUser/<int:id>", methods=['GET', 'POST'])
@login_required
def edit_user(id):
    user = User.query.get(id)
    Form = Edit_user_form()
    if Form.validate_on_submit():
        username = Form.username.data
        password = Form.password.data
        email = Form.email.data
        admin_dao.editUser(id, username, password, email)
        return redirect(url_for('admin.list_User'))
    Form.username.data = user.username
    Form.password.data = user.password
    Form.email.data = user.e_mail
    return render_template("console/edit_user.html", user_id=id, form=Form)


@admin_bp.route("/admin/listNote/", methods=['GET'])
@login_required
def list_Note():
    note_list = admin_dao.query_note()
    return render_template("console/list_note.html", notes=note_list)


@admin_bp.route("/admin/deleteNote/<int:id>")
@login_required
def del_Note(id):
    admin_dao.deleteNoteById(id)
    return redirect(url_for('admin.list_Note'))


@admin_bp.route("/admin/login/", methods=['GET', 'POST'])
def admin_login():
    form = Admin_Login_form()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        remember = form.remember.data
        admin = Admin.query.filter_by(username=username).first()
        if admin and admin.password == password:
            if login_user(admin, remember=remember):
                flash('登录成功', category='info')
                return redirect(url_for('admin.list_User'))
            else:
                flash('用户不存在或密码错误，请重新登录', category='danger')
        else:
            flash('用户不存在或密码错误，请重新登录', category='danger')
    return render_template("console/admin_login.html", form=form)
